<template>
  <div class="music-playerdetail">
    <el-button @click="backplaylist" icon="el-icon-close" class="closebtn" type="danger" circle></el-button>
    <div class="music-lyric-icon">
      <!-- cd转动图片部分 -->
      <div class="lyric-view">
        <div class="img-wrap">
          <div class="changzhen pointer" :class="{ 'changzhen-active': musicisPlay }">
            <img src="../../assets/changzhen.png" alt="" />
          </div>
          <div class="changpian changpian-active" ref="changpian">
            <div class="changpian-wrap">
              <img :src="musicIcon + '?param=180y180'" />
            </div>
          </div>
        </div>
      </div>

      <!-- 歌词部分 -->
      <div class="music-lyric">
        <p class="title">{{currentMusic.name}}</p>
        <div class="authors">
          <p v-for="(item,index) of musicauthor" :key="index+'author2'"
            @click.stop="$router.push({ name: 'artistAccount', query: { id:item.id } });" class="author">{{item.name}}
          </p>
        </div>
        <div @click="$router.push({ name:'album',query:{ id:musicAlbum.id }})" class="album">
          {{musicAlbum.name}}
        </div>
        <div class="lyric-wrap" ref="lyricWrapRef">
          <p v-for="(item,index) in nowlyric.lines" :key="index" class="text-hidden"
            :class="{lyric_active: index === nowlyric.curren}">
            {{item.txt}}
          </p>
        </div>
      </div>
      <!-- 关联部分 -->
      <div class="music-about">

      </div>
    </div>
    <!-- 评论部分 -->
    <div class="music-comment">
      <div class="textarea-input">
        <el-input type="textarea" maxlength="140" show-word-limit :rows="4" placeholder="请输入内容" v-model="textarea">
        </el-input>
        <el-button :disabled="disabled" @click="getcomment" plain>评论</el-button>
      </div>
      <div class="hotcomment-title" v-if="hotcomment[0]">
        <h3>精彩评论</h3>
      </div>
      <div class="hotcomment">
        <comment @reply="reply" :detail="item" v-for="(item,index) of hotcomment" :key="index" />
      </div>
      <div class="comment-title">
        <h3>最新评论({{commentCount}})</h3>
      </div>
      <div class="comment">
        <comment :type="0" @reply="reply" :id="currentMusic.id" :detail="item" v-for="(item,index) of comment"
          :key="index" />
      </div>
      <div class="pageset" @click="commenterror()">
        <el-pagination disabled :page-size.sync="pageSize" :current-page.sync="curPage" layout="prev, pager, next"
          :total="commentCount" background>
        </el-pagination>
      </div>
      <el-button @click="backtop" icon="el-icon-top" class="upbtn" type="info" circle></el-button>
    </div>

  </div>

</template>
<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { mapState } from "vuex";
import { getmusiclyricAPI } from "@/api/music";
import lyric from "@/utils/lyric";
import comment from "@/components/comment";
import { getmusiccommentAPI } from "@/api/music";
import { sendcommentAPI } from "@/api/comment.js";
export default {
  name: "music-playerdetail",
  //import引入的组件需要注入到对象中才能使用
  components: { comment },
  props: {},
  data() {
    //这里存放数据
    return {
      musiclyric: "",
      nowlyric: "",

      // 评论用属性
      textarea: "",
      comment: "",
      hotcomment: "",
      disabled: false,
      curPage: 1,
      pageSize: 30,
      commentCount: 0,
    };
  },
  //计算属性 类似于data概念
  computed: {
    ...mapState([
      "currentMusic",
      "currentMusicUrl",
      "musicisPlay",
      "currentTimesecond",
    ]),
    lyric() {
      if (this.nowlyric == "") {
        return "暂无歌词";
      }

      return this.nowlyric;
    },

    musicIcon() {
      if (this.currentMusic) {
        return this.currentMusic.al.picUrl;
      } else {
        return "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png";
      }
    },
    // 获取音乐作者
    musicauthor() {
      if (this.currentMusic) {
        if (this.currentMusic.ar) {
          let name = [];
          this.currentMusic.ar.forEach((element) => {
            name.push(element);
          });
          return name;
        }
        return "作者";
      } else {
        return "作者";
      }
    },
    musicAlbum() {
      if (this.currentMusic) {
        return this.currentMusic.al;
      }
      return {
        name: "专辑",
        id: "0",
      };
    },
  },
  //监控data中的数据变化
  watch: {
    currentMusic: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getmusiclyric();
          this.getcommentmusic();
        }
      },
    },
    currentTimesecond(time) {
      if (this.nowlyric != "") {
        this.setmusiclyricposition(time);
      }
    },
    // 用于控制唱片转动与暂停
    musicisPlay(val) {
      if (!val) {
        this.$refs.changpian.style.animationPlayState = "paused";
      } else if (val) {
        this.$refs.changpian.style.animationPlayState = "running";
      }
    },
  },
  //方法集合
  methods: {
    backtop() {
      document.documentElement.scrollTop = 0;
    },
    backplaylist() {
      this.$router.go(-1);
    },
    // 获取歌词
    async getmusiclyric() {
      const data = await getmusiclyricAPI(this.currentMusic.id);
      if (data.data.code !== 200) return this.$message.error("获取歌词失败");
      this.musiclyric = data.data;
      this.nowlyric = new lyric(this.musiclyric.lrc.lyric);
    },
    // 判断歌词位置
    setmusiclyricposition(time) {
      // 进度条随着时间前进
      // 判断是否到达尽头，并且当当前事件大于一下行时间的时候换行
      if (
        this.nowlyric.curren != this.nowlyric.total - 1 &&
        time > this.nowlyric.lines[this.nowlyric.curren + 1].time
      ) {
        this.nowlyric.curren++;
        // 因为每次time变动只会调用一次，歌词只会逐行递增,通过回调函数实现快进功能，使歌词直接定位到对应的行
        if (
          this.nowlyric.curren != this.nowlyric.total - 1 &&
          time > this.nowlyric.lines[this.nowlyric.curren + 1].time
        ) {
          this.setmusiclyricposition(time);
        }
        this.lyricHanlder(this.nowlyric.curren);
      }
      // 当进度条回滚的时候，
      else if (
        this.nowlyric.curren != 0 &&
        time < this.nowlyric.lines[this.nowlyric.curren].time
      ) {
        this.nowlyric.curren--;
      }
      // 为快进设计的回调函数
      if (
        this.nowlyric.curren != 0 &&
        time < this.nowlyric.lines[this.nowlyric.curren].time
      ) {
        this.setmusiclyricposition(time);
      }
      this.lyricHanlder(this.nowlyric.curren);
    },
    /* 歌词行数变化的回调 */
    lyricHanlder(lineNum) {
      if (lineNum > 4) this.scrollAnimation(lineNum - 4);
      else this.$refs.lyricWrapRef.scrollTop = 0;
    },
    /* 歌词滚动动画 */
    scrollAnimation(line) {
      const step = () => {
        this.$refs.lyricWrapRef.scrollTop = line * 40;
      };
      window.requestAnimationFrame(step);
    },
    // 评论回复
    reply(commentId) {
      // console.log(commentId);
      this.$prompt("输入回复内容", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(async ({ value }) => {
          if (value != null) {
            const data = await sendcommentAPI(
              2,
              0,
              this.currentMusic.id,
              value,
              commentId
            );
            // console.log(data);
            if (data.data.code === 200) {
              this.textarea = "";
              this.disabled = false;
              this.$message({
                type: "success",
                message: "发送成功" + value,
              });
            }
            if (data.data.code === 400) {
              this.$message({
                type: "error",
                message: "发送失败",
              });
            }
          } else {
            this.$message({
              type: "error",
              message: "评论不能为空",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    async getcommentmusic() {
      try {
        const data = await getmusiccommentAPI(this.currentMusic.id);
        if (data.data.code != 200) {
          this.$message.error("获取评论失败");
          return;
        }
        this.commentCount = data.data.total;
        this.comment = data.data.comments;
        let hotcomment = data.data.hotComments;
        let limit = hotcomment.length - 10;
        hotcomment.splice(10, limit);
        this.hotcomment = hotcomment;
      } catch (error) {
        console.log(error + "获取评论列表失败");
      }
    },
    // 发送评论
    async getcomment() {
      try {
        this.disabled = true;
        const data = await sendcommentAPI(
          1,
          0,
          this.currentMusic.id,
          this.textarea
        );
        // console.log(data);
        if (data.data.code === 200) {
          this.textarea = "";

          this.disabled = false;
        }
      } catch (error) {
        console.log(error);
      }
    },
    commenterror() {
      this.$message.error("更多精彩评论，请去APP端查看");
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getcommentmusic();
    document.documentElement.scrollTop = 0;
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    document.title = this.currentMusic.al.name + " - 歌曲 - 音乐播放器";
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {
    // console.log("歌曲详情页面销毁");
  }, //生命周期 - 销毁完成
  activated() {
    // console.log("歌曲详情页面激活");
  }, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang='less'>
.music-playerdetail {
  //为音乐播放器留位置
  padding-bottom: 90px;
  margin: 0 auto;
  min-width: 1300px;
  background: linear-gradient(#ececec, 10%, white);

  .closebtn {
    position: absolute;
    margin-top: 50px;
    margin-left: 50px;
    z-index: 10;
  }

  .music-lyric-icon {
    position: relative;
    display: flex;
    justify-content: center;
    margin-bottom: 30px;
    padding-top: 30px;
  }
  .music-lyric {
    .title {
      text-align: center;
      font-size: 30px;
      margin-bottom: 10px;
      color: #474747;
    }
    .album {
      color: #acacac;
      cursor: pointer;
      font-size: 17px;
      text-align: center;
      margin-bottom: 10px;
    }
    .album:hover {
      color: #2246aa;
    }
    .authors {
      display: flex;
      justify-content: center;
      .author {
        margin-right: 10px;
        text-align: center;
        font-size: 17px;
        margin-bottom: 10px;
        color: #acacac;
        cursor: pointer;
      }
      .author:hover {
        color: #2246aa;
      }
    }
  }
  .lyric_active {
    font-weight: bold;
    font-size: 25px;
    color: rgb(57, 166, 255);
  }
  ::-webkit-scrollbar {
    width: 5px;
  }
  ::-webkit-scrollbar-thumb {
    background-color: rgb(182, 182, 182);
    border-radius: 5px;
  }
  .lyric-wrap {
    text-align: center;
    width: 600px;
    height: 400px;
    overflow-y: scroll;
    scrollbar-width: thin;
    margin: 0 auto;
    color: #666666;
    font-size: 17px;
    line-height: 40px;
    transition: all 0.8s linear;
    p {
      // height: 40px;
    }
    @media screen and(max-width:768px) {
      .lyric-wrap {
        width: 100%;
        margin: 20px auto;
        font-size: 13px;
        p {
          height: 40px;
        }
      }
    }
  }
  //歌曲关联
  .music-about {
    width: 260px;
    height: 200px;
  }
  /* 唱片区域 */
  .lyric-view {
    margin-top: 50px;
    display: flex;

    .img-wrap {
      position: relative;

      .changzhen {
        position: absolute;
        top: -20px;
        left: 130px;
        width: 120px;
        transform-origin: 3px 3px;
        transition: all 0.5s;
        z-index: 20;

        img {
          width: 120px;
        }
      }

      .changpian {
        margin-top: 40px;
        width: 260px;
        height: 260px;
        border-radius: 50%;
        background-color: #c4c3c6;
        display: flex;
        justify-content: center;
        align-items: center;

        .changpian-wrap {
          width: 240px;
          height: 240px;
          background-color: #1a1c1e;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        img {
          width: 180px;
          height: 180px;
          border-radius: 50%;
        }
      }
    }
  }

  .changzhen-active {
    transform: rotate(30deg);
  }

  .changpian-active {
    animation: circle 30s infinite linear;
  }

  @keyframes circle {
    from {
      transform: rotate(0);
    }
    to {
      transform: rotate(360deg);
    }
  }
}
.music-comment {
  margin: 0 auto;
  width: 1200px;
  .upbtn {
    position: fixed;
    bottom: 100px;
    right: 200px;
  }
  .hotcomment-title {
    margin-top: 20px;
    margin-bottom: 20px;
  }
  .comment-title {
    margin-top: 20px;
    margin-bottom: 20px;
  }
  .textarea-input {
    display: flex;
    justify-content: space-between;
    .el-textarea {
      margin-right: 30px;
      /deep/.el-textarea__inner {
        min-height: 99px;
        max-height: 99px;
      }
    }
  }
  .pageset {
    display: flex;
    justify-content: center;
    .el-pagination {
      margin-top: 50px;
      margin-bottom: 80px;
    }
  }
}
</style>